package com.aitaoxue.palx.api;

import android.content.Context;
import android.util.Log;

import com.aitaoxue.palx.util.TLog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class ApiHttpClient {
	public static final String HOST = "";
	private static String API_URL = "http://120.25.202.14/pal_studio/index.php/V2/%s";

	// 获取图片地址前缀
	public static final String IMG_URL_PREFIX = "http://palstorage.oss-cn-shenzhen.aliyuncs.com/";
	// 获取头像前缀
	public static final String HEADER_PREFIX = "http://120.25.202.14/pal_studio/Uploads/head_thumb/User/";
	// 错题本前缀
	public static final String ERROR_BOOK_PREFIX = "http://120.25.202.14/pal_studio/Uploads/errorBook/";

	public static final String SERVER_PROTOCOL = "http://www.itaoxue.me/pal_studio/index.php/About/ServiceProtocol.html";

	public static final String DELETE = "DELETE";
	public static final String POST = "POST";
	public static final String GET = "GET";
	public static final String PUT = "PUT";
	public static AsyncHttpClient client;

	public ApiHttpClient() {
	}

	public static AsyncHttpClient getHttpClient() {
		return client;
	}

	public static void cancelAll(Context context) {
		client.cancelRequests(context, true);
	}

	public static void clearUserCookies(Context context) {

	}

	public static String getAbsoluteApiUrl(String partUrl) {
		String url = String.format(API_URL, partUrl);
		Log.d("BASE_CLIENT", "requset:" + url);
		return url;
	}

	public static String getApiUrl() {
		return API_URL;
	}

	public static void get(String partUrl, AsyncHttpResponseHandler handler) {
		client.get(getAbsoluteApiUrl(partUrl), handler);
		log(new StringBuilder("GET ").append(partUrl).toString());
	}

	public static void get(String partUrl, RequestParams params,
			AsyncHttpResponseHandler handler) {
		client.get(getAbsoluteApiUrl(partUrl), params, handler);
		log(new StringBuilder("GET ").append(partUrl).append("&")
				.append(params).toString());
	}

	public static void post(String partUrl, AsyncHttpResponseHandler handler) {
		client.post(getAbsoluteApiUrl(partUrl), handler);
		// client.post(getAbsoluteApiUrl(partUrl), handler);
		log(new StringBuilder("POST ").append(partUrl).toString());
	}

	public static void post(String partUrl, RequestParams params,
			AsyncHttpResponseHandler handler) {
		client.post(getAbsoluteApiUrl(partUrl), params, handler);
		log(new StringBuilder("POST ").append(partUrl).append("&")
				.append(params).toString());
	}

	public static void log(String log) {
		TLog.log("BaseApi", log);
	}

	public static void setHttpClient(AsyncHttpClient c) {
		client = c;
	}

	public static void setCookie(String cookie) {
		client.addHeader("cookie", cookie);
	}

}
